package cn.itsource.pethome.user.controller;

import cn.itsource.pethome.Basic.util.AjaxResult;
import cn.itsource.pethome.user.constant.WechatConstant;
import cn.itsource.pethome.user.domain.dto.WechatUserDto;
import cn.itsource.pethome.user.service.IWechatService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.Map;

@Controller
@RequestMapping("/wechat")
public class WechatController {
    @Autowired
    private IWechatService wechatService;
    /**
     * 获取授权码
     * @return
     */
    @RequestMapping("/toLogin")
    public String toLogin(){
        //获取授权码
        String code = WechatConstant.CODEURL.replace("APPID", WechatConstant.APPID)
                .replace("REDIRECT_URI", WechatConstant.REDIRECT_URI);
        System.out.println(code);
        return "redirect:"+code;
    }

    /**
     * 回调
     * @param code
     * @return
     */
    @RequestMapping("/callback")
    public String callback(String code){
        return "redirect:http://localhost:8081/callback.html？code="+code;
    }

    /**
     * 通过code获取access_token
     * @param param
     * @return
     */
    @RequestMapping("/accessToken")
    @ResponseBody
    public AjaxResult accessToken(@RequestBody Map<String,String> param){
        //获取code
        try {
            String code = param.get("code");
            //获取url地址
            Map<String,Object> map = wechatService.handleCallback(code);
            return new AjaxResult().setResult(map);
        } catch (Exception e) {
            e.printStackTrace();
            return new AjaxResult(false,e.getMessage());
        }
    }

    /**
     * 绑定微信
     * @param wechatUserDto
     * @return
     */
    @PostMapping("/binder")
    @ResponseBody
    public AjaxResult binder(@RequestBody WechatUserDto wechatUserDto){
        try {
            Map<String,Object> map = wechatService.binder(wechatUserDto);
            return new AjaxResult().setResult(map);
        } catch (Exception e) {
            e.printStackTrace();
            return new AjaxResult(false,e.getMessage());
        }
    }

}
